<template>
  <div class="index-container pc-container">
    <IndexArticle :data="data.article" :detail="detail"></IndexArticle>
  </div>
  <div class="index-container mobile-container">
    <CommonArticle :detail="detail" :article="data.article"></CommonArticle>
  </div>
</template>

<script setup lang="ts">
import { onMounted, onUnmounted, reactive } from 'vue';
import { _getTopArticle } from '../index.service.ts';
import { ArticleListVO } from '../index.ts';

import { useRouter } from 'vue-router';
import Crypoto from '@/utils/encrypted.ts';
import { useDialog } from 'crane-element';
import PasswordCheck from '@/pages/index/password/PasswordCheck.vue';
import IndexArticle from '@/pages/index/show-index/IndexArticle.vue';
import CommonArticle from '@/components/CommonArticle.vue';

const cry: any = new Crypoto();

const { openDialog } = useDialog();
const router = useRouter();

const minWidth = 1160;

const data = reactive({
  article: {
    id: '',
    viewCount: 0,
    coverPathDesc: getImage('default_cover'),
    tagNames: ['欢迎'],
    title: '欢迎光临',
    content: '欢迎来到北极星博客',
    creatorAvatar: getImage('default_logo'),
    creatorName: '',
    gmtCreate: '2023-01-01 12:02:09'
  } as ArticleListVO,
  isPC: true
});

function getImage(name: string) {
  const url = new URL(`../../../assets/${name}.jpeg`, import.meta.url);
  return url.pathname;
}

onMounted(() => {
  getTop();
  handleResize();
  window.addEventListener('resize', handleResize);
});

onUnmounted(() => {
  window.removeEventListener('resize', handleResize);
});

const getTop = () => {
  _getTopArticle().then((res) => {
    if (res.data) {
      data.article = res.data;
    }
  });
};

function detail(id: string, isPassword: boolean) {
  if (isPassword) {
    openDialog({
      component: PasswordCheck,
      options: {
        destroyOnClose: true,
        width: data.isPC ? '50%' : '100%'
      },
      params: {}
    }).then((res: any) => {
      if (res) {
        router.push(
          `/article-detail/${id}+${cry.encrypt(res.password, 'crane-nb-class')}`
        );
      }
    });
  } else {
    router.push(`/article-detail/${id}`);
  }
}

function handleResize() {
  data.isPC = window.innerWidth > minWidth;
}
</script>

<style scoped lang="less">
@media (max-width: 1161px) {
  /* 在宽度小于或等于 1035px 的屏幕上应用以下样式 */
  /* 在这里添加你的样式规则 */
  .pc-container {
    display: none;
  }

  .mobile-container {
    display: block;
  }

  .index-container {
    width: 100%;
    height: 360px;
    position: relative;
    margin-top: 20px;
    margin-bottom: 20px;
  }
}

@media (min-width: 1160px) {
  /* 在宽度大于 1035px 的屏幕上应用以下样式 */
  /* 在这里添加你的样式规则 */
  .pc-container {
    display: block;
  }

  .mobile-container {
    display: none;
  }

  .index-container {
    width: 100%;
    height: 450px;
    position: relative;
    margin-top: 20px;
    margin-bottom: 20px;
  }
}
</style>
